/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.wsinfra.wsa.impl;

import javax.xml.namespace.QName;

import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlException;

import cgl.narada.wsinfra.exception.ParsingException;
import cgl.narada.wsinfra.schemas.addressing.ActionDocument;
import cgl.narada.wsinfra.schemas.addressing.FaultToDocument;
import cgl.narada.wsinfra.schemas.addressing.FromDocument;
import cgl.narada.wsinfra.schemas.addressing.MessageIDDocument;
import cgl.narada.wsinfra.schemas.addressing.RelatesToDocument;
import cgl.narada.wsinfra.schemas.addressing.ReplyAfterDocument;
import cgl.narada.wsinfra.schemas.addressing.ReplyToDocument;
import cgl.narada.wsinfra.schemas.addressing.ToDocument;
import cgl.narada.wsinfra.schemas.soap.EnvelopeDocument;
import cgl.narada.wsinfra.schemas.soap.EnvelopeType;
import cgl.narada.wsinfra.schemas.soap.HeaderType;
import cgl.narada.wsinfra.util.QNameLocator;
import cgl.narada.wsinfra.wsa.AddressingHeaders;
import cgl.narada.wsinfra.wsa.ParseWsaHeaders;

/** This is a utility class which takes an XmlCursor and retrives all the
    WS-Addressing headers that can be located.

    @author Shrideep Pallickara
    $Date: 2005/07/29 22:41:30 $
    $Revision: 1.9 $
*/

public class ParseWsaHeadersImpl implements ParseWsaHeaders {
  private static final ParseWsaHeaders instance = new ParseWsaHeadersImpl();
  private QNameLocator qNameLocator;
  private String wsaUri = "http://schemas.xmlsoap.org/ws/2004/08/addressing";

  private String moduleName = "ParseWsaHeadersImpl: ";

  private ParseWsaHeadersImpl() {
    qNameLocator = QNameLocator.getInstance();
  }


  public static ParseWsaHeaders getInstance() {
    return instance;
  }


  /** This method retrives the WS-Addressing headers that are available within
      this XmlCursor */
  public AddressingHeaders 
  getAddressingHeaders(EnvelopeDocument envelopeDocument)
    throws ParsingException {
    EnvelopeType envelopeType = envelopeDocument.getEnvelope();
    if (envelopeType == null) {
      throw new ParsingException(moduleName + "The Envelope type is NULL");
    }


    if ( !envelopeType.isSetHeader() ) {
      throw 
	new ParsingException(moduleName + 
			     "There is no Header element within the envelope");
    }

    HeaderType headerType = envelopeType.getHeader();
    XmlCursor headerCursor = headerType.newCursor();
   
    /** Create a moveTo cursor, since the cursor may be positioned somewhere 
	else after we locate the qName, and also since the elements may appear
	out-of-order */
    XmlCursor moveTo = headerType.newCursor();
    AddressingHeadersImpl addressingHeaders = new AddressingHeadersImpl();

    parseForActionElement(headerCursor, addressingHeaders);
    
    headerCursor.toCursor(moveTo);
    parseForFromElement(headerCursor, addressingHeaders);
    

    headerCursor.toCursor(moveTo);
    parseForToElement(headerCursor, addressingHeaders);
    
    
    headerCursor.toCursor(moveTo);
    parseForReplyToElement(headerCursor, addressingHeaders);
    
    
    headerCursor.toCursor(moveTo);
    parseForFaultToElement(headerCursor, addressingHeaders);


    headerCursor.toCursor(moveTo);
    parseForRelatesToElement(headerCursor, addressingHeaders);


    headerCursor.toCursor(moveTo);
    parseForMessageIDElement(headerCursor, addressingHeaders);

    headerCursor.dispose();
    moveTo.dispose();
    return addressingHeaders;
  }


  /** Repostions the cursor to a previously established bookmark */
  private void repositionCursorToBookmark(XmlCursor cursor,
					  XmlCursor.XmlBookmark bookmark) {
    boolean movedToBookmark = cursor.toBookmark(bookmark);
    if (!movedToBookmark ) {
      System.out.println(moduleName +
			 "Unable to move to previously created bookmark");
    }

    //System.out.println(cursor.currentTokenType().isEnddoc() );
    System.out.println(cursor.xmlText());
  }


  
  /** Retrive the [wsa:Action] from within the SOAP envelope. If this 
      element IS NOT present a null is returned. If the element IS present 
      and if there are problems parsing the element a parsing exception is 
      thrown. */
  public ActionDocument
  getAction(EnvelopeDocument envelopeDocument) 
    throws ParsingException {
    XmlCursor headerCursor = getHeaderCursor(envelopeDocument);
    AddressingHeadersImpl addressingHeaders = new AddressingHeadersImpl();
    
    parseForActionElement(headerCursor, addressingHeaders);
    
    headerCursor.dispose();
    return addressingHeaders.getAction();
  }


  
  /** Retrive the [wsa:From] from within the SOAP envelope. If this 
      element IS NOT present a null is returned. If the element IS present 
      and if there are problems parsing the element a parsing exception is 
      thrown. */
  public FromDocument
  getFrom(EnvelopeDocument envelopeDocument)
    throws ParsingException {
    XmlCursor headerCursor = getHeaderCursor(envelopeDocument);
    AddressingHeadersImpl addressingHeaders = new AddressingHeadersImpl();
    
    parseForFromElement(headerCursor, addressingHeaders);
    
    headerCursor.dispose();
    return addressingHeaders.getFrom();
  }



  
  /** Retrive the [wsa:To] from within the SOAP envelope. If this 
      element IS NOT present a null is returned. If the element IS present 
      and if there are problems parsing the element a parsing exception is 
      thrown. */
  public ToDocument
  getTo(EnvelopeDocument envelopeDocument)
    throws ParsingException {
    XmlCursor headerCursor = getHeaderCursor(envelopeDocument);
    AddressingHeadersImpl addressingHeaders = new AddressingHeadersImpl();
    
    parseForToElement(headerCursor, addressingHeaders);
    
    headerCursor.dispose();
    return addressingHeaders.getTo();
  }



  
  /** Retrive the [wsa:ReplyTo] from within the SOAP envelope. If this 
      element IS NOT present a null is returned. If the element IS present 
      and if there are problems parsing the element a parsing exception is 
      thrown. */
  public ReplyToDocument
  getReplyTo(EnvelopeDocument envelopeDocument)
    throws ParsingException {
    XmlCursor headerCursor = getHeaderCursor(envelopeDocument);
    AddressingHeadersImpl addressingHeaders = new AddressingHeadersImpl();
    
    parseForReplyToElement(headerCursor, addressingHeaders);
    
    headerCursor.dispose();
    return addressingHeaders.getReplyTo();
  }


  
  
  /** Retrive the [wsa:ReplyAfter] from within the SOAP envelope. If this 
      element IS NOT present a null is returned. If the element IS present 
      and if there are problems parsing the element a parsing exception is 
      thrown. */
  public ReplyAfterDocument
  getReplyAfter(EnvelopeDocument envelopeDocument)
    throws ParsingException {
    XmlCursor headerCursor = getHeaderCursor(envelopeDocument);
    AddressingHeadersImpl addressingHeaders = new AddressingHeadersImpl();
    
    parseForReplyAfterElement(headerCursor, addressingHeaders);
    
    headerCursor.dispose();
    return addressingHeaders.getReplyAfter();
  }


  
  
  /** Retrive the [wsa:FaultTo] from within the SOAP envelope. If this 
      element IS NOT present a null is returned. If the element IS present 
      and if there are problems parsing the element a parsing exception is 
      thrown. */
  public FaultToDocument
  getFaultTo(EnvelopeDocument envelopeDocument)
    throws ParsingException {
    XmlCursor headerCursor = getHeaderCursor(envelopeDocument);
    AddressingHeadersImpl addressingHeaders = new AddressingHeadersImpl();
    
    parseForFaultToElement(headerCursor, addressingHeaders);
    
    headerCursor.dispose();
    return addressingHeaders.getFaultTo();
  }
  



  /** Retrive the [wsa:RelatesTo] from within the SOAP envelope. If this 
      element IS NOT present a null is returned. If the element IS present 
      and if there are problems parsing the element a parsing exception is 
      thrown. */
  public RelatesToDocument
  getRelatesTo(EnvelopeDocument envelopeDocument)
    throws ParsingException {
    XmlCursor headerCursor = getHeaderCursor(envelopeDocument);
    AddressingHeadersImpl addressingHeaders = new AddressingHeadersImpl();

    parseForRelatesToElement(headerCursor, addressingHeaders);
    
    headerCursor.dispose();
    return addressingHeaders.getRelatesTo();
  }



  
  /** Retrive the [wsa:MessageID] from within the SOAP envelope. If this 
      element IS NOT present a null is returned. If the element IS present 
      and if there are problems parsing the element a parsing exception is 
      thrown. */
  public MessageIDDocument
  getMessageID(EnvelopeDocument envelopeDocument)
    throws ParsingException {
    XmlCursor headerCursor = getHeaderCursor(envelopeDocument);
    AddressingHeadersImpl addressingHeaders = new AddressingHeadersImpl();
    
    parseForMessageIDElement(headerCursor, addressingHeaders);
    
    headerCursor.dispose();
    return addressingHeaders.getMessageID();
  }




  /** This method retrives the WS-Addressing headers that are available within
      this XmlCursor */
  private XmlCursor
  getHeaderCursor(EnvelopeDocument envelopeDocument)
    throws ParsingException {
    EnvelopeType envelopeType = envelopeDocument.getEnvelope();
    if (envelopeType == null) {
      throw new ParsingException(moduleName + "The Envelope type is NULL");
    }
    
    
    if ( !envelopeType.isSetHeader() ) {
      throw 
	new ParsingException(moduleName + 
			     "There is no Header element within the envelope");
    }
    
    HeaderType headerType = envelopeType.getHeader();
    XmlCursor headerCursor = headerType.newCursor();
    
    return headerCursor;
  }




  /** Check to see if the Action Element can be retrieved and the proceed
      to put this element, if available, into the AddressingHeaders */
  private void
  parseForActionElement(XmlCursor cursor,
			AddressingHeadersImpl addressingHeaders)
    throws ParsingException {

    QName qName = new QName(wsaUri, "Action");
    boolean actionFound = qNameLocator.locateQName(cursor, qName);

    if (!actionFound) {
      return;
    }

    try {
      ActionDocument actionDocument =
	ActionDocument.Factory.parse(cursor.xmlText());
       addressingHeaders.setAction(actionDocument);
    } catch (XmlException xmlEx) {
      throw new ParsingException(moduleName + xmlEx.toString());
    }

  } /* end parse Action element */




  /** Check to see if the From Element can be retrieved and the proceed
      to put this element, if available, into the AddressingHeaders */
  private void
  parseForFromElement(XmlCursor cursor,
		      AddressingHeadersImpl addressingHeaders)
    throws ParsingException {

    QName qName = new QName(wsaUri, "From");
    boolean fromFound = qNameLocator.locateQName(cursor, qName);

    if (!fromFound) {
      return;
    }

    try {
      FromDocument fromDocument =
	FromDocument.Factory.parse(cursor.xmlText());
      addressingHeaders.setFrom(fromDocument);
    } catch (XmlException xmlEx) {
      throw new ParsingException(moduleName + xmlEx.toString());
    }

  } /* end parse From element */



  /** Check to see if the To Element can be retrieved and the proceed
      to put this element, if available, into the AddressingHeaders */
  private void
  parseForToElement(XmlCursor cursor,
		    AddressingHeadersImpl addressingHeaders)
    throws ParsingException {

    QName qName = new QName(wsaUri, "To");
    boolean toFound = qNameLocator.locateQName(cursor, qName);

    if (!toFound) {
      return;
    }

    try {
      ToDocument toDocument =
	ToDocument.Factory.parse(cursor.xmlText());
      addressingHeaders.setTo(toDocument);
    } catch (XmlException xmlEx) {
      throw new ParsingException(moduleName + xmlEx.toString());
    }

  } /* end parse To element */




  /** Check to see if the ReplyTo Element can be retrieved and the proceed
      to put this element, if available, into the AddressingHeaders */
  private void
  parseForReplyToElement(XmlCursor cursor,
			 AddressingHeadersImpl addressingHeaders)
    throws ParsingException {

    QName qName = new QName(wsaUri, "ReplyTo");
    boolean replyToFound = qNameLocator.locateQName(cursor, qName);

    if (!replyToFound) {
      return;
    }

    try {
      ReplyToDocument replyToDocument =
	ReplyToDocument.Factory.parse(cursor.xmlText());
      addressingHeaders.setReplyTo(replyToDocument);
    } catch (XmlException xmlEx) {
      throw new ParsingException(moduleName + xmlEx.toString());
    }

  } /* end parse ReplyTo element */



  /** Check to see if the ReplyAfter Element can be retrieved and the proceed
      to put this element, if available, into the AddressingHeaders */
  private void
  parseForReplyAfterElement(XmlCursor cursor,
			    AddressingHeadersImpl addressingHeaders)
    throws ParsingException {

    QName qName = new QName(wsaUri, "ReplyAfter");
    boolean replyAfterFound = qNameLocator.locateQName(cursor, qName);

    if (!replyAfterFound) {
      return;
    }

    try {
      ReplyAfterDocument replyAfterDocument =
	ReplyAfterDocument.Factory.parse(cursor.xmlText());
      addressingHeaders.setReplyAfter(replyAfterDocument);
    } catch (XmlException xmlEx) {
      throw new ParsingException(moduleName + xmlEx.toString());
    }

  } /* end parse ReplyAfter element */





  /** Check to see if the FaultTo Element can be retrieved and the proceed
      to put this element, if available, into the AddressingHeaders */
  private void
  parseForFaultToElement(XmlCursor cursor,
			 AddressingHeadersImpl addressingHeaders)
    throws ParsingException {

    QName qName = new QName(wsaUri, "FaultTo");
    boolean faultToFound = qNameLocator.locateQName(cursor, qName);

    if (!faultToFound) {
      return;
    }

    try {
      FaultToDocument faultToDocument =
	FaultToDocument.Factory.parse(cursor.xmlText());
      addressingHeaders.setFaultTo(faultToDocument);
    } catch (XmlException xmlEx) {
      throw new ParsingException(moduleName + xmlEx.toString());
    }

  } /* end parse FaultTo element */





  /** Check to see if the RelatesTo Element can be retrieved and the proceed
      to put this element, if available, into the AddressingHeaders */
  private void
  parseForRelatesToElement(XmlCursor cursor,
			   AddressingHeadersImpl addressingHeaders)
    throws ParsingException {

    QName qName = new QName(wsaUri, "RelatesTo");
    boolean relatesToFound = qNameLocator.locateQName(cursor, qName);

    if (!relatesToFound) {
      return;
    }

    try {
      RelatesToDocument relatesToDocument =
	RelatesToDocument.Factory.parse(cursor.xmlText());
      addressingHeaders.setRelatesTo(relatesToDocument);
    } catch (XmlException xmlEx) {
      throw new ParsingException(moduleName + xmlEx.toString());
    }

  } /* end parse RelatesTo element */





  /** Check to see if the MessageID Element can be retrieved and the proceed
      to put this element, if available, into the AddressingHeaders */
  private void
  parseForMessageIDElement(XmlCursor cursor,
			   AddressingHeadersImpl addressingHeaders)
    throws ParsingException {

    QName qName = new QName(wsaUri, "MessageID");
    boolean messageIDFound = qNameLocator.locateQName(cursor, qName);

    if (!messageIDFound) {
      return;
    }

    try {
      MessageIDDocument messageIDDocument =
	MessageIDDocument.Factory.parse(cursor.xmlText());
      addressingHeaders.setMessageID(messageIDDocument);
    } catch (XmlException xmlEx) {
      throw new ParsingException(moduleName + xmlEx.toString());
    }

  } /* end parse MessageID element */



}
